/**
 * Copyright 2014,Peak Tai 台俊峰(taijunfeng_it@sina.com).
 * 
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
 * use this file except in compliance with the License. You may obtain a copy of
 * the License at
 * 
 * 		http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations under
 * the License.
 */

package com.cenluan.blog;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Page;

public class BlogsService {
	/**
	 * 分页查询博客
	 * 
	 * @param pn
	 * @param state
	 * @param criteria
	 * @param createrId
	 * @param order
	 * @return
	 */
	static Page<Blog> paginate(int pn, String criteria, String createrId,
			String order) {
		StringBuilder sql = new StringBuilder();
		List<Object> paras = new ArrayList<Object>();
		sql.append(" from t_blog b ");
		sql.append(" left join t_user u ");
		sql.append(" on u.id=b.createrId ");
		if ("hot".equals(order)) {
			sql.append(" left join ( ");
			sql.append(" select count(*) ct,blogId ");
			sql.append(" from t_blog_favorite ");
			sql.append(" group by blogId ");
			sql.append(" ) s on s.blogId=b.id ");
		}
		sql.append(" where b.state=? ");
		paras.add(Blog.STATE_ACTIVE);
		if (StrKit.notBlank(createrId)) {
			sql.append(" and b.createrId=? ");
			paras.add(createrId);
		} else {
			sql.append(" and b.privacy=0 ");
		}
		if (StrKit.notBlank(criteria)) {
			sql.append(" and (b.title like ? or u.nickname like ?)");
			paras.add("%" + criteria + "%");
			paras.add("%" + criteria + "%");
		}
		if (StrKit.notBlank(createrId)) {
			sql.append(" and b.createrId=? ");
			paras.add(createrId);
		}
		if ("hot".equals(order)) {
			sql.append(" order by s.ct desc ");
		} else {
			sql.append(" order by b.updateTime desc ");
		}

		return Blog.dao.paginate(pn, 20, "select b.*", sql.toString(),
				paras.toArray());

	}

	/**
	 * 获取用户最后一次创建博客的时间
	 * 
	 * @param userId
	 * @return
	 */
	static Date getLastCreateBlogTime(String userId) {
		return Db.queryDate("select max(createTime) "
				+ "from t_blog where createrId=?", userId);
	}

	/**
	 * 是否已经添加收藏
	 * 
	 * @param userId
	 * @param blogId
	 * @return
	 */
	static boolean hasBeenAddedFavorite(String userId, String blogId) {
		return Db.queryLong("select count(*) from t_blog_favorite "
				+ "where blogId=? and userId=?", blogId, userId) == 1;
	}
	
	
}
